package jinyilw.tools.net.file;

import jinyilw.common.log.LogTools;

import java.io.IOException;
import java.net.SocketAddress;

public class FileTransferClient extends FileTransfer implements Runnable
{
	private Thread listenThread;
	private volatile boolean threadRun = false;

	public FileTransferClient(String host, int port)
	{
		super(host, port);
	}

	public FileTransferClient(SocketAddress host)
	{
		super(host);
	}

	public void startConnectInThread()
	{
		new Thread(this::startConnect).start();
	}

	@Override
	public synchronized boolean startConnect()
	{
		if (threadRun)
			return true;
		createConnect();
		boolean isConnected = isConnected();
		if (isConnected)
		{
			threadRun = true;
			listenThread = new Thread(this);
			listenThread.start();
		}
		return isConnected;
	}

	@Override
	public synchronized void stopConnect()
	{
		threadRun = false;
		if (listenThread != null)
			listenThread.interrupt();
		super.stopConnect();
	}

	@Override
	public boolean isConnected()
	{
		return socketChannel != null;
	}

	@Override
	public void run()
	{
		if (isConnected())
			LogTools.info("文件传输客户端连接成功...");
		while (threadRun)
		{
			try
			{
				update(200);
			} catch (IOException e)
			{
				super.stopConnect();
				LogTools.debug("文件传输客户端断开连接!", e);
				break;
			}
		}
		threadRun = false;
	}
}
